package com.hj.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.hj.config.ConfigConstants;
import com.hj.model.FileAttribute;
import com.hj.service.FilePreview;
import com.hj.util.PdfUtils;
import com.hj.web.filter.BaseUrlFilter;

/**
 * @author dehui dou
 * @date 2020/10/3 19:16
 * @description office类型处理实现类
 */
@Service
public class PdfFilePreviewImpl implements FilePreview {

    @Autowired
    private PdfUtils pdfUtils;

    /**
     * @author dehui dou
     * @description 文件预览处理实现
     * @param model
     * @param fileAttribute
     * @return java.lang.String
     */
    @Override
    public String filePreviewHandle(Model model, FileAttribute fileAttribute) {
        String fileName = fileAttribute.getFileViewName();
        // 预览Type，参数传了就取参数的，没传取系统默认
        String officePreviewType = model.asMap().get("officePreviewType") == null
            ? ConfigConstants.getOfficePreviewType() : model.asMap().get("officePreviewType").toString();
        String baseUrl = BaseUrlFilter.getBaseUrl();
        String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "pdf";
        String outFilePath = ConfigConstants.getFileDir() + pdfName;
        if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType)
            || OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType)) {
            List<String> imageUrls = pdfUtils.pdf2jpg(outFilePath, pdfName, baseUrl);
            if (imageUrls == null || imageUrls.size() < 1) {
                model.addAttribute("msg", "pdf转图片异常，请联系管理员");
                model.addAttribute("fileType", ".pdf");
                return "fileNotSupported";
            }
            model.addAttribute("imgurls", imageUrls);
            model.addAttribute("currentUrl", imageUrls.get(0));
            if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType)) {
                return "officePicture";
            } else {
                return "picture";
            }
        } else {
            model.addAttribute("pdfUrl", pdfName);
            return "pdf";
        }
    }
}
